from pynput import keyboard
import pyautogui 
import pathlib
import threading
import time
import sys,os
import random

fl=True
confidence=0.9
root=pathlib.Path(os.path.dirname(os.path.realpath(sys.argv[0])))
picdir=root/"audiocontent"

sys.path.append(str(root.parent/"loger"))
import loger
log = loger.Logger('audiocontent',StreamLevel='debug',FileLevel='info').logger

def delay(n):
    
    if(n==0):
        n=int(random.random()*5)+0
    for i in range(n):
        if(key_listen_thread.is_alive()):
            print(n-i)
        else:
            sys.exit()
        time.sleep(1)

def on_press(key):
    global fl
    try:
        print(f'字母键 {key.char} 被按下，按q键退出')
        if(key.char == "q"):
            print(f'exit')
            fl=False
            sys.exit()
    except AttributeError:
        print(f'特殊键 {key} 被按下')
 
def on_release(key):
    global fl
    print(f'{key} 被释放')
    if key == keyboard.Key.esc:
        # 停止监听
        fl=False
        return False
 
# 收集事件直到按下了 Esc 键
def listen_key():
    with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()
key_listen_thread=threading.Thread(target=listen_key)
key_listen_thread.start()

def findpic(filename:str):
    global confidence
    p=pyautogui.locateOnScreen(str(picdir/filename),confidence=confidence)
    return p

p1=findpic("01.PNG")
p2=findpic("02.PNG")
def clickpic(filename:str,doubleClick_:bool=False):
    global confidence
    p=pyautogui.locateOnScreen(str(picdir/filename),confidence=confidence)
    if p is not None:
        pyautogui.moveTo(pyautogui.center(p))
        pyautogui.click()
        time.sleep(0.1)
        if(doubleClick_):
            pyautogui.moveTo(pyautogui.center(p))
            pyautogui.click()
            time.sleep(0.1)
    else:
        log.error(f"{filename}未找到")
        
while(fl):
    print(time.time())
    clickpic("01.PNG",True)
    clickpic("02.PNG")
    clickpic("03.PNG")
    delay(0)
